﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ToWaDBFirst.Models;

namespace ToWaDBFirst.Controllers
{
    /**
     * Controller to handle message creation.
     **/
    [Authorize]
    public class MessageController : Controller
    {
        ToWaDBFirstDBEntities2 db = new ToWaDBFirstDBEntities2();
        ToWaService service = new ToWaService();
        
        /**
         * Method to create a message. As long as there's either input from the users field or the groups field the
         * request will be put through then redirect back to the /Home/Index. If no users or groups are found, redirect
         * back to the NewMessage View.
         **/
        // POST: /Message/Create

        [HttpPost]
        public ActionResult Create(NewMessageWrapper newMessageWrapper)
        {
            try
            {
                List<int> userIds = new List<int>();
                if(newMessageWrapper.users != null)
                {
                    List<string> userNames = newMessageWrapper.users.Split(';').ToList();
                    userIds = service.GetUserIds(userNames);
                }
                if (newMessageWrapper.groups != null)
                {
                    List<string> groupNames = newMessageWrapper.groups.Split(';').ToList();
                    userIds.AddRange(service.GetUserIdsInGroup(groupNames));
                }
                if (userIds.Count() > 0)
                {
                    int messageId = service.CreateMessage(newMessageWrapper, User.Identity.Name);
                    service.SendMessageToUser(messageId, userIds);

                    return RedirectToAction("Index", "Home");
                }
                ViewBag.ErrorThing = "Didn't return.";
                return View();
            }
            catch
            {
                return View();
            }
        }
        
        // GET: /Message/Create
        public ActionResult Create()
        {
            return View();
        }
    }
}
